package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.ExchangeHisAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.AdvertListData;
import com.wbao.dianniu.listener.IAdvertListListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.AdvertListManager;
import com.wbao.dianniu.scrollview.PullToRefreshView;
import com.wbao.dianniu.update.ExchangeHisHelper;
import com.wbao.dianniu.utils.Notification;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 积分兑换
 * <p>
 * Created by yejianjun on 2018/11/12.
 */

public class ExchangeActivity extends BaseActivity implements IAdvertListListener, ExchangeHisHelper.IExchangeHistListener, PullToRefreshView.OnFooterRefreshListener, View.OnClickListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private PullToRefreshListView pullListView;
    private ListView myListView;
    private ExchangeHisAdapter adapter;
    private Button rmbExchangeBtn;
    private Button adExchangeBtn;
    private Dialog dialog;
    private AdvertListManager manager;
    private int currentPage = 0;
    private int PAGE_COUNTS = 10;
    private boolean IsPullDown = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_exchange, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.exchange));
        initWattingView();
        initView();
        initData();
        reqData();
    }

    private void initView() {
        pullListView = findViewById(R.id.exchange_pull_refresh_view);
        pullListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullListView.setOnRefreshListener(onRefreshListener);
        myListView = pullListView.getRefreshableView();
        myListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
        registerForContextMenu(myListView);
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void addHeadView() {
        View headView = LayoutInflater.from(this).inflate(R.layout.exchange_fragment_headview, null);
        rmbExchangeBtn = (Button) headView.findViewById(R.id.exchange_rmb_btn);
        adExchangeBtn = (Button) headView.findViewById(R.id.exchange_ad_btn);
        initListener();
        myListView.addHeaderView(headView);

    }


    private void initData() {
        addHeadView();
        manager = new AdvertListManager(this);
        manager.addAdvertListListener(this);
        adapter = new ExchangeHisAdapter(this);
        adapter.setData(new ArrayList<AdvertListData>());
        myListView.setAdapter(adapter);
    }

    PullToRefreshBase.OnRefreshListener2 onRefreshListener = new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh() {
            pullDownRequest();
        }

        @Override
        public void onPullUpToRefresh() {
            pullUpRequest();
        }
    };


    // 上拉刷新数据请求
    private void pullUpRequest() {
        IsPullDown = false;
        //没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        reqData();
    }

    private void pullDownRequest() {
        IsPullDown = true;
        currentPage = 0;
        reqData();
    }


    private void reqData() {
        manager.advertList(currentPage * PAGE_COUNTS, PAGE_COUNTS);
    }

    private void initListener() {
        GlobalUserData userData = new GlobalUserData();
        if (userData.getScore() >= 300) {
            rmbExchangeBtn.setTextColor(getResources().getColor(R.color.blue_text));
            adExchangeBtn.setTextColor(getResources().getColor(R.color.blue_text));
        } else {
            rmbExchangeBtn.setTextColor(getResources().getColor(R.color.black));
            adExchangeBtn.setTextColor(getResources().getColor(R.color.black));
        }
        rmbExchangeBtn.setOnClickListener(this);
        adExchangeBtn.setOnClickListener(this);
        ExchangeHisHelper.getInstance().addListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        GlobalUserData userData = new GlobalUserData();
        switch (v.getId()) {
            case R.id.exchange_ad_btn:
                if (1 == userData.getPartner()) {
                    if (userData.getScore() >= 300) {
                        // 跳转到发广告界面
                        Intent intent = new Intent();
                        intent.setClass(this, SendAdActivity.class);
                        startActivity(intent);
                    } else {
                        showMsg(getResources().getString(R.string.no_enough_score_remark));
                    }
                } else {
                    showMsg(getResources().getString(R.string.no_partner_remark));
                }
                break;
            case R.id.exchange_rmb_btn:
                if (1 == userData.getPartner()) {
                    if (userData.getScore() >= 300) {
                        // 弹出兑换框
                        exchangeRMB();
                    } else {
                        showMsg(getResources().getString(R.string.no_enough_score_remark));
                    }
                } else {
                    showMsg(getResources().getString(R.string.no_partner_remark));
                }
                break;
            case R.id.copy_weichat_button:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(getResources().getString(R.string.weichat));
                Notification.showToastMsg(this, "微信号已复制");
                break;
            case R.id.save_qrcode_button:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                saveQrCodeBitmap(this);
                break;
            default:
                break;
        }


    }

    @Override
    public void onAdvertListFailure(int errorCode, String errorMsg) {
        pullListView.onRefreshComplete(false, false);
    }

    @Override
    public void onAdvertListSuccess(List<AdvertListData> list) {
        pullListView.onRefreshComplete(false, false);
        if (null != list) {
            if (IsPullDown) {
                adapter.clear();
            }
            adapter.addData(list);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void addOneExchange(AdvertListData data) {
        adapter.addFootOneData(data);
    }

    @Override
    public void removeOneExchange(int id) {
        adapter.removeOneData(id);
    }

    @Override
    public void modifyOneExchange(int id, AdvertListData data) {
        adapter.modifyOneData(id, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeAdvertListListener(this);
        }
        ExchangeHisHelper.getInstance().removeListener(this);
    }

    private void showMsg(String msg) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle(msg);
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void saveQrCodeBitmap(final Context context) {
        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {

                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.exchange_rmb_qrcode);
                    File appDir = new File(Environment.getExternalStorageDirectory(), "DnImage");
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    String fileName = System.currentTimeMillis() + ".jpg";
                    File file = new File(appDir, fileName);
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        ScannerByMedia(context, file.getAbsolutePath());
                        if (!bmp.isRecycled()) {
                            System.gc(); // 通知系统回收
                        }
                    }
                    return file.getAbsolutePath();
                } else {
                    Notification.showToastMsg(context, "未检测到存储卡，无法保存");
                    return null;
                }

            }

            @Override
            protected void onPostExecute(Object o) {
                if (null != o) {
                    Notification.showToastMsg(context, "图片已保存到:" + o);
                }
            }
        }.execute();

    }

    /**
     * MediaScanner 扫描更新图库图片
     **/
    private static void ScannerByMedia(Context context, String path) {
        MediaScannerConnection.scanFile(context, new String[]{path}, null, null);
        Log.v("TAG", "media scanner completed");
    }

    private void exchangeRMB() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // instantiate the dialog with the custom Theme
        dialog = new Dialog(this, R.style.custom_Dialog);
        View layout = inflater.inflate(R.layout.exchange_rmb_dialog, null);
        Button copyBtn = (Button) layout.findViewById(R.id.copy_weichat_button);
        Button saveBtn = (Button) layout.findViewById(R.id.save_qrcode_button);
        copyBtn.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        currentPage++;
        reqData();
    }
}
